package com.bwie.car.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.car.feign.UserFeign;
import com.bwie.car.mapper.CarMapper;
import com.bwie.car.service.CarService;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.*;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * @Author：杨鹏
 * @Package：com.bwie.car.service.impl
 * @Project：yp_zhoukao723
 * @name：CarServiceImpl
 * @Date：2024/7/23 9:47
 */
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result listCar(Car car) {
        List<Car> carList = carMapper.listCar(car);
        return Result.success(carList);
    }

    @Transactional
    @Override
    public Result addRecords(Car car) {
        // 行程记录添加
        Integer i = carMapper.addRexcords(car);
        // 当自行车状态为正在使用时，用车按钮禁用
        carMapper.updCarId(car);
        return i>0?Result.success():Result.error();
    }

    @Transactional
    @Override
    public Result updRecords(Records records) {

        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        User user1 = JSONObject.parseObject(user, User.class);

        Car car = new Car();
        car.setCarId(records.getCarId());
        car.setStatusId(1);
        // 用车时长：当前时间-用车开始时间，单位为分钟，数据计算正确（5分）
        Integer recordsDuration = records.getRecordsDuration();

        // 行驶距离：用车时长×0.8，结果计算正确（5分）
        records.setRecordsDistance(recordsDuration * 0.8);
        Double recordsDistance = records.getRecordsDistance();
        // 费用计算公式：（车型公里单价）×公里数+0.1×用车时间（单位分钟），车型公里单价（入门山地每公里1元，入门公路车每公里1.2元，专业山地车每公里1.3元，专业公路车每公里1.6元）
        Double price = 0.0;
        if ("入门公里车".equals(records.getTypeName())){
            price = 1.0;
        }
        if ("入门山地车".equals(records.getTypeName())){
            price = 1.2;
        }
        if ("专业公路车".equals(records.getTypeName())){
            price = 1.3;
        }
        if ("专业山地车".equals(records.getTypeName())){
            price = 1.6;
        }
        // 费用计算正确（4分）
        records.setRecordsPrice(price * recordsDuration + 0.1 * recordsDistance);
        Double recordsPrice = records.getRecordsPrice();
        Integer i = carMapper.updRecords(records);
        // 点击结束行程，自行车列表对应自行车状态变更为未使用（5分）
        carMapper.updCarCarId(car);
        // 点击结束行程，扣除用户余额对应费用
        user1.setUserPrice(recordsPrice);
        userFeign.updUser(user1);

        // 点击结束行程后，使用消息队列发送短信通知用户
        rabbitTemplate.convertAndSend("yp_723_mq","",message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
            return message;
        });

        return i>0?Result.success():Result.error();
    }

    @Override
    public Result listType() {
        List<Type> typeList = carMapper.listType();

        return Result.success(typeList);
    }

    @Override
    public Result listStatus() {
        List<Status> statusList = carMapper.listStatus();
        return Result.success(statusList);
    }

    @Override
    public Result listRecords() {
        List<Records> recordsList = carMapper.listRecords();
        return Result.success(recordsList);
    }


}
